/** api */
import * as SettingTaskApi from '@src/api/SettingTaskApi';
/** model */
import { nodeTypeList, FlowEnum} from '@model/enum/FlowEnum';
import { generateNode, getAddNodePopoverTypeList } from '@src/modules/setting/task/taskTypeSetting/flow/util/flowNodeFun';
import processList from '@src/modules/setting/task/taskTypeSetting/flow/model/const/flowMapV2.js';
import { store } from "@src/component/business/BizFlowProcessChart/src/constant.js"
/** util */
import { getRootWindow } from '@src/util/dom'
import _ from 'lodash';
import TaskOverTimeSetting from "@model/types/setting/task/TaskOverTimeSetting";

//内置节点
const BUILT_SYSTEM_NODES = [ FlowEnum.START, FlowEnum.REVIEW, FlowEnum.COST ];

export const TaskFlowMap = {
  create: 'created',
  allot: 'allocated',
  accept: 'accepted',
  start: 'processing',
  finish: 'finished',
  cost: 'costed'
}

export default {
  data() {
    return {
      nodeTypeList,
      flowProcessList:[],
      currentNode: {},
      loading: true,
      commonNode: [],
      isEditState: false,
      commonData: {},
      oldFlowProcessList: [],
      normalNodeIdsHasSave: [], // 保存一下已经存储的自定义节点id,用于判断当前添加的节点是否是新加的（因为添加的节点自动生成id，无法根据id判断）
      oldFlowCardList: [],
      oldApproveSetting: {},
    };
  },
  computed: {
    /** 是否开启新工单流程权限 */
    isHaveNodeFlowAuth() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskFlowExtend ?? false;
    },
    /** 是否是公共节点且存在公共节点中*/
    isAlreadySavedCommon() {
      return  this.currentNode?.isCommon == 1 && this.isCommonNodeExist
    },
    /** 当前节点是否存在于公共节点中 */
    isCommonNodeExist() {
      return this.commonNode.some(item => item.id == this.currentNode.id);
    },
    /* 节点是否新添加的*/
    isNewNormalNode() {
      return this.normalNodeIdsHasSave?.findIndex(item => item === this.currentNode?.id) < 0
    }
  },
  mounted() {
    // 初始化工单流程配置
    if(this.isHaveNodeFlowAuth) {
      this.$eventBus.$on('init_flow_setting_task', this.getTaskFlowNode);
      this.getTaskCommonNode();
    }
  },
  methods: {
    /** 节点添加之前的校验 */
    async beforeAddNode(newNode) {
      try {
        const params = {
          tableName: newNode.id,
          typeId: this.taskTypeId,
          isCommonNode: true
        }
        const res = await SettingTaskApi.checkCommonNodeAdd(params);
        
        if (res.succ && !res.data){
          this.$message.warning(res.message);
          return false; 
        }
        return true;
      } catch (error) {
        return true;
      }
    },
    /** 删除当前节点之前 */
    async beforeDeleteNode(args) {
      this.currFlow = 'create';
      this.initNodeInfo()
    },
    /**编辑公共节点 */
    editCommonNodes() {
      const { flowSetting, currentNode } = this;
      this.commonData = {
        flowSetting: _.cloneDeep(this.flowSetting),
        currentNode: _.cloneDeep(this.currentNode)
      }
      this.oldFlowCardList = _.cloneDeep(this.flowCardList)
      this.oldApproveSetting = _.cloneDeep(this.flowSetting?.approveSetting)
      this.isEditState = true;
    },
    onCancelEdit() {
      if(this.isEditState) {
        this.flowCardList = this.oldFlowCardList;
      }
      this.isEditState = false;
    },
    /** 提交公共节点 */
    async onSubmitCommon() {
      try {
        let confirm = await this.$platform.confirm(i18n.t('common.form.setting.flowNodeSetting.des5'));
        if(!confirm) return;

        const { currentNode, flowSetting } = this.commonData;
        this.flowProcessList.forEach(item => {
          if(item.id == currentNode.id){
            item.data = flowSetting;
            item.title = currentNode.title
          }
        })
      } catch(e) {
        console.log(e)
      } finally {
        this.isEditState = false;
      }
    },
    /** 取消公共节点配置 */
    async cancelNodeCommonSetting() {

      let confirm = await this.$platform.confirm(i18n.t('common.form.setting.cancelFlowNodeCommonSettingTips', {data1:this.currentNode.title}));
      if(!confirm) return;
       
      this.currentNode.isCommon = 0;
    },
    /** 校验流程必填 */
    checkProcessingRequired() {
      const needCheckProcessing = this.flowProcessList.filter(item => {
        const data = item.data || {};
        return item.type === FlowEnum.NORMAL && (!data?.nodeResponsiblePerson?.length || !data.nodeStateName || !data.nodeBtnName  || !item.title);
      });
      if (needCheckProcessing?.length > 0) {
        this.$platform.notification({
          title: this.$t('task.setting.taskTypeSetting.flow.tabs.tip8', {data1: needCheckProcessing?.[0].title }),
          type: 'error'
        });
        return true;
      }

      return false;
    },
    /** 保存后端需要的系统节点数据 */
    handleSaveSystemProcessing() {
      const flowSetting = this.taskFlowData?.taskTypeConfig?.flowSetting || {};
      for (const key of Object.keys(flowSetting)) {
        const sameNode = this.flowProcessList.find(item => item.type === key) || {};
        if (Object.keys(sameNode).length) {
          flowSetting[key] = sameNode?.data ?? {};
          flowSetting[key].state = true;
        } else {
          if(BUILT_SYSTEM_NODES.includes(key)) {
            flowSetting[key].state = false;
          }
        }
      }
    },
    /** 初始化流程线  */
    convertProcessData() {
      const flowSetting = this.taskFlowData?.taskTypeConfig?.flowSetting || {};
      const newProcessList = processList.filter(node=> flowSetting?.[node.type].state) || [];

      newProcessList.forEach((item,index) => {
        if(Object.keys(item?.data || {}).length === 0) {
          item.data = flowSetting?.[item.type] || {}
        }
        if (index < newProcessList.length - 1) {
          item.targetId = newProcessList[index + 1].id;
        }
      })
      this.flowProcessList = newProcessList;
      this.initNodeInfo();
    },
   /** 初始化当前节点的信息 */
    initNodeInfo() {
      if(this.currentNode?.id && !this.flowProcessList?.some(item=>item.id == this.currentNode?.id)) {
        this.currFlow = 'create'
      }
      // 当前节点
      const currentNode = this.flowProcessList.find(item=>{
        if(this.currFlow == 'create') return item.type == this.currFlow
        if(this.currentNode?.id) return item.type == this.currFlow && item.id == this.currentNode.id
        return item.type == this.currFlow
      }) || {};

      this.currentNode = currentNode;
      store.currFlow = currentNode
    },
    /** 点击流程节点 */
    handleNodeContentClick(node) {
      this.onCancelEdit();
      this.currFlow = node.type
      this.currentNode = node;
    },
    /** 根据上一个节点的类型添加节点弹窗数据 */
    handleNodePopoverTypeClick(preType, addNodeTypeList) {
      store.addNodeTypeData = getAddNodePopoverTypeList(preType, addNodeTypeList);
    },
    /**
     * 创建自定义节点
     * @param nodeList 所有节点
     * @param node 当前节点
     * @param nextData 下一个节点
     * @param insertNode  插入的节点
     */
    handleCustomCreateNode(nodeList, node, nextData, insertNode) {

      // 生成构建对应节点需要的参数
      let nodeDataConfig = this.generateNodeDefaultAttribute(insertNode) || {};

      if ( insertNode.type ==  FlowEnum.NORMAL && !insertNode?.isCommon )  {
        nodeDataConfig.nodeStateName = insertNode.title

        nodeDataConfig.nodeResponsiblePerson = [{
          name: i18n.t('task.taskTypes.allot.taskExecutor'),
          id: 'EXECUTOR_USER',
          type: "5"
        }]
      }
      const generateNewNodes = generateNode({ nodeList, node, nextData, insertNode, genNodeParams:{ data: nodeDataConfig } });
      // 重新生成下一节点id
      node.targetId = generateNewNodes.id;
      return generateNewNodes
    },
   /** 对应的节点需要的数据（初始化） */
    generateNodeDefaultAttribute(insertNode) {
      // 初始化超时数据
      let overTime = Object.assign(new TaskOverTimeSetting(), {remindType: null, isAhead: 1, minutes: 15, overTime: 0})
      return this.taskFlowData?.taskTypeConfig?.flowSetting?.[insertNode.type] || ({...overTime, ...insertNode.data});
    },
    /** 获取工单流程节点*/ 
    async getTaskFlowNode(isNeedInit = true) {
      try {
        const params = {
          taskId: '',
          taskTypeId: this.taskTypeId
        }
        let { success, result = [] } = await SettingTaskApi.getTaskFlowNode(params);
        if(success) {
          if(result.length > 0){
            result.forEach(item => {
              const { type, isCommon } = item;
              const curNode = processList.find(f => type === f.type) || {};
              // 处理icon
              if(type === FlowEnum.NORMAL){
                item.icon = isCommon === 1 ? 'iconfont icon-gonggongjiedian' :'iconfont icon-liuchengjiedian';
              }else {
                item.icon = curNode.icon
              }
              // 处理系统节点
              if(type !== FlowEnum.NORMAL) {
                const flowSetting = this.taskFlowData?.taskTypeConfig?.flowSetting || {}
                item.data = flowSetting?.[type] ?? {};
              }
            });
            this.flowProcessList = result;
            this.normalNodeIdsHasSave = this.flowProcessList?.map(item => item.id) ?? []

            this.oldFlowProcessList = _.cloneDeep(this.flowProcessList);

            // 需要初始化当前节点
            if(isNeedInit) {
              this.initNodeInfo();
            }
            return
          }

          this.convertProcessData(result);
        }
      } catch(error){
        console.log(error)
      } finally {
        this.loading = false;
      }
    },
    /** 保存流程节点*/ 
    async createTaskFlowNode() {
      try {
        let flows = _.cloneDeep(this.flowProcessList)

        // 处理附加组件数据
        try {
          flows = flows?.map(item => {
            // 如果是新添加的公共节点，不能设置commonNodeCardIds，会把之前commonNodeCardIds的值丢了
            if(item.isCommon == 1 && !this.normalNodeIdsHasSave.includes(item.id)) {
              return item
            }
            // 处理附加组件的值
            const key = item?.type === 'normal' ? item.id : (TaskFlowMap?.[item.type] ?? item.type)
            let commonNodeCardIds = []
            this.flowCardList?.forEach(card => {
              if(card.stateCanEdit?.includes(key)) {
                commonNodeCardIds.push(card.id)
              }
            })
            this.$set(item.data, 'commonNodeCardIds', commonNodeCardIds)
            return item;
          })
        }catch (e) {
          console.error(e)
        }

        const params = {
          taskTypeId: this.taskTypeId,
          nodeList: flows,
        }

        let { success, result = [], message } = await SettingTaskApi.createTaskFlowNode(params);

        await this.getTaskFlowNode(false);
        this.getTaskCommonNode();

        if(!success) {
          this.$message.warning(message)
          // 报错当前节点需要更新数据超时的数据
          if(this.currentNode?.id && this.currentNode?.type === 'normal') {
            const overTime = this.flowProcessList.find(item=> item.id === this.currentNode.id)?.data?.overTime ?? ''
            this.$set(this.currentNode.data, 'overTime', overTime)

            // this.flowProcessList需要保留之前填写的数据，所以更新下
            this.flowProcessList = this.flowProcessList?.map(item => {
              if(item.id === this.currentNode.id ) item = this.currentNode
              return item;
            })
          }
          return true;
        }

      }catch(error){
        console.log(error)
      }
    },
    /** 获取公共节点信息 */
    async getTaskCommonNode() {
      try {
        const { success, result = [] } = await SettingTaskApi.getTaskCommonNode();
        if (success) {
          this.commonNode = result.map(({ id, title, type, isSystem, isCommon, data = {} }) => ({
            id,
            type,
            title,
            icon: 'iconfont icon-gonggongjiedian',
            isSystem,
            isCommon,
            data,
          })) || [];

          for (const item of this.nodeTypeList) {
            if (item.type === 'public') {
              item.list = this.commonNode ;
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
    }
  },
  beforeDestroy() {
    this.$eventBus.$off('init_flow_setting_task', this.getTaskFlowNode);
  },

};
